/*
 * Unidata Platform
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 *
 * Commercial License
 * This version of Unidata Platform is licensed commercially and is the appropriate option for the vast majority of use cases.
 *
 * Please see the Unidata Licensing page at: https://unidata-platform.com/license/
 * For clarification or additional options, please contact: info@unidata-platform.com
 * -------
 * Disclaimer:
 * -------
 * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
 * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
 * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
 * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
 * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
 */
package org.unidata.mdm.rest.v1.data.ro.serializer;

import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidata.mdm.data.exception.DataExceptionIds;
import org.unidata.mdm.rest.system.ro.SimpleDataType;
import org.unidata.mdm.rest.system.serializer.AbstractJsonDeserializer;
import org.unidata.mdm.rest.v1.data.ro.LargeObjectRO;
import org.unidata.mdm.rest.v1.data.ro.attributes.SimpleAttributeRO;
import org.unidata.mdm.system.exception.PlatformFailureException;

/**
 * @author Michael Yashin. Created on 03.06.2015.
 */
public class SimpleAttributeDeserializer extends AbstractJsonDeserializer<SimpleAttributeRO> {

    /**
     * The logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleAttributeDeserializer.class);

    @Override
    public SimpleAttributeRO deserialize(JsonParser jsonParser,
                            DeserializationContext deserializationContext) throws IOException {

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        JsonNode nameNode = node.get("name");
        JsonNode typeNode = node.get("type");
        JsonNode valueNode = node.get("value");
        JsonNode unitIdNode = node.get("unitId");
        JsonNode valueIdNode = node.get("valueId");

        if (nameNode == null) {
            throw new JsonMappingException(jsonParser, "SimpleAttributeRO: Name node is required");
        }

        if (typeNode == null) {
            throw new JsonMappingException(jsonParser, "SimpleAttributeRO: Type node is required");
        }

        if (valueNode == null) {
            throw new JsonMappingException(jsonParser, "SimpleAttributeRO: Value node is required");
        }

        if ((unitIdNode == null && valueIdNode != null) || (unitIdNode != null && valueIdNode == null)) {
            throw new JsonMappingException(jsonParser, "SimpleAttributeRO: Measured options should be define completely");
        }

        SimpleDataType type = SimpleDataType.fromValue(typeNode.asText());
        SimpleAttributeRO attr = new SimpleAttributeRO();
        attr.setValueId(valueIdNode == null || valueIdNode.isNull() ? null : valueIdNode.asText());
        attr.setUnitId(unitIdNode == null || unitIdNode.isNull() ? null : unitIdNode.asText());
        attr.setName(nameNode.asText());
        attr.setType(type);

        if (!valueNode.isNull()) {
            switch (type) {
                case BOOLEAN:
                    attr.setValue(valueNode.asBoolean());
                    break;
                case DATE:
                    try {
                        attr.setValue(parseToLocalDate(valueNode.asText()));
                    } catch (PlatformFailureException e) {
                        LOGGER.warn("Cannot convert attribute {} of type {} [{}]. Exception {}.",
                                attr.getName(),
                                attr.getType(),
                                valueNode.asText(),
                                e);
                    }
                    break;
                case TIME:
                    try {
                        attr.setValue(parseToLocalTime(valueNode.asText()));
                    } catch (PlatformFailureException e) {
                        LOGGER.warn("Cannot convert attribute {} of type {} [{}]. Exception {}.",
                                attr.getName(),
                                attr.getType(),
                                valueNode.asText(),
                                e);
                    }
                    break;
                case TIMESTAMP:
                    try {
                        attr.setValue(parseToLocalDateTime(valueNode.asText()));
                    } catch (PlatformFailureException e) {
                        LOGGER.warn("Cannot convert attribute {} of type {} [{}]. Exception {}.",
                                attr.getName(),
                                attr.getType(),
                                valueNode.asText(),
                                e);
                    }
                    break;
                case INTEGER:
                    attr.setValue(valueNode.asLong());
                    break;
                case NUMBER:
                    attr.setValue(valueNode.asDouble());
                    break;
                case STRING:
                    attr.setValue(valueNode.asText());
                    break;
                case BLOB:
                case CLOB:
                    if (valueNode.getNodeType() != JsonNodeType.OBJECT) {
                        throw new PlatformFailureException("Invalid LOB object received from front end [%s].",
                                DataExceptionIds.EX_DATA_INVALID_LOB_OBJECT, valueNode.toString());
                    }

                    Iterator<String> i = valueNode.fieldNames();
                    if (i.hasNext()) {
                        LargeObjectRO obj = new LargeObjectRO();
                        while (i.hasNext()) {
                            String field = i.next();
                            JsonNode lobNode = valueNode.get(field);

                            switch (field) {
                                case "id":
                                    obj.setId(lobNode.textValue());
                                    break;
                                case "fileName":
                                    obj.setFileName(lobNode.textValue());
                                    break;
                                case "mimeType":
                                    obj.setMimeType(lobNode.textValue());
                                    break;
                                case "size":
                                    obj.setSize(lobNode.longValue());
                                    break;
                                default:
                                    break;
                            }
                        }
                        attr.setValue(obj);
                    }
                    break;
                default:
                    throw new PlatformFailureException("Unsupported data type: " + type.name(),
                            DataExceptionIds.EX_DATA_UNSUPPORTED_DATA_TYPE, type);
            }
        }
        return attr;
    }
}
